package com.example.boot.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.boot.mapper.UserRoleMapper;
import com.example.boot.pojo.entity.Role;
import com.example.boot.pojo.entity.RoleMenu;
import com.example.boot.pojo.entity.UserRole;
import com.example.boot.pojo.result.Result;
import com.example.boot.service.RoleMenuService;
import com.example.boot.service.RoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description:
 * @author: mhpy
 * @date 2022/8/6 22:07
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMenuService roleMenuService;

    @GetMapping("/getRole")
    public Result get(){
        List<Role> list = roleService.list();
        return Result.success().data("item",list);
    }

    @PreAuthorize("hasAnyAuthority('system:role:add','system:role:edit')")
    @PostMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody Role role){
        roleService.saveOrUpdate(role);
        return Result.success();
    }

    @PreAuthorize("hasAuthority('system:role:delete')")
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable Integer id){
        roleService.removeById(id);
//        角色删除对应的要删除于此角色相关的用户角色表和角色菜单表中的数据
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId,id));
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId,id));
        return Result.success();
    }

//    当前角色已有的菜单 菜单回显

    @GetMapping("currentRoleMenu/{id}")
    public Result currentRoleMenu(@PathVariable Integer id){
        List<Integer> roleMenuList = roleService.getCurrentRoleMenuIdList(id);
        return Result.success().data("item",roleMenuList);
    }
}
